from datetime import datetime
import hashlib
import uuid
from flask import request
from base import base # 绝对导入 base 蓝图和模型
from flask import jsonify
from extensions import db
from models import User
from flask_login import login_user, logout_user, login_required, \
    current_user

@base.route("/user/register", methods=["POST"])
def register():
    if User.query.filter_by(username = request.json['username']).first():
        return jsonify({'msg': '新建用户失败，用户名已存在！', 'code': 500})

    user = User()

    user.id = str(uuid.uuid4()).replace("-", "")

    md = hashlib.md5()
    md.update(request.json['password'].encode('utf-8'))
    user.password = md.hexdigest()
    user.create_time = datetime.now()
    with db.session.no_autoflush:
        if 'nickName' in request.json: user.nick_name = request.json['nickName'] 
        if 'username' in request.json: user.username = request.json['username']
        db.session.add(user)
        db.session.commit()
    return jsonify({'msg': '新建用户成功', 'code': 200})




@base.route('/user/login', methods=['POST'])
def do_login():
    #检查用户名是否存在
    user = User.query.filter_by(username=request.json['username']).first()
    
    if user is not None:
        md = hashlib.md5()
        #提交的密码MD5加密
        md.update(request.json['password'].encode('utf-8'))
        #MD5加密后的内容同数据库密码比较
        if md.hexdigest() == user.password:
            login_user(user)
            return jsonify({'msg': '登录成功~', 'code': 200})
        
    return jsonify({'msg': '登录失败,账号密码错误~', 'code': 500})


@base.route('/user/check_login', methods=['GET'])
def check_login():
    print(current_user)
    if current_user.is_authenticated:
        return jsonify({
            'msg': 'ok', 
            'code': 200,
            'data':{
                'logged_in': True,
                'user': {
                    'id': current_user.get_id(),
                    'username': current_user.username,
                    'nickName': current_user.nick_name,
                    # 添加更多需要返回的用户信息
                }
            }
            
        })
    else:
        return jsonify({'msg': '用户未登录', 'code': 200,'data':{'logged_in': False}})
